<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: joomleague.class.php 1126 2008-06-09 05:45:04Z julienv $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 
global $database, $mainframe;
if(!defined('_joomleague_func_')){
  
  define('_joomleague_func_', 1);
  
  // definitions of constants we should use instead of global vars
  // constants coming directly from joomla have an undercore before name
  define ( '_JOOMLA_JL_PATH', $mainframe->getCfg('absolute_path'));
  
  define ( '_JOOMLA_JL_LIVE_SITE', $mainframe->getCfg('live_site'));
  
  define ( '_JL_LOCALE', $mainframe->getCfg( 'locale' ));
  
  define ( '_JL_LIST_LIMIT', $mainframe->getCfg( 'list_limit' ));
 
  // patch for 1.5. lang isn't always (never ?) set.
  if ( $mainframe->getCfg( 'lang' ) != '' ) {
    define ( '_JL_LANG', $mainframe->getCfg( 'lang' ));
  }
  else {
    define ( '_JL_LANG', 'english' );
  }
  
  // next is for compatibility with former used constant
  define ( 'JLLIVEURL', _JOOMLA_JL_LIVE_SITE);
  // compatibility ends
  
  // this devides components in two parts: league_management or prediction_management
  define( 'JL_ADMIN_MODE', mosGetParam($_REQUEST,'adminmode', 'league_management'));
  // end of adminmode
  
  //we need encoding for template config and ajax editing
  $iso = split( '=', _ISO );
  define ( '_JL_ENCODING', $iso[1]);
  //now encoding is defined, we do not have to split it everytime it is used
  
  define ( 'JL_ADMIN_PATH', _JOOMLA_JL_PATH.'/administrator/components/com_joomleague' );
  // next is for compatibility with former used constant
  define ( 'JLADMINBASEPATH', JL_ADMIN_PATH);
  // compatibility ends
  
  define ( 'JL_FRONTEND_PATH', _JOOMLA_JL_PATH.'/components/com_joomleague' );
  
  define ( 'JLBASEPATH', JL_FRONTEND_PATH);
  
  define ( 'JL_OPTION', mosGetParam($_REQUEST, 'option', 'com_joomleague'));
  
  define ( 'JL_CONFIG_PATH', JL_FRONTEND_PATH.'/frontend_config'); 
  
  define ( 'JL_URL_FOLDER', _JOOMLA_JL_LIVE_SITE.'/components/com_joomleague');
  
  define ( 'JL_COMPONENT_LINK', 'index.php?option=com_joomleague');
  
  define ( 'JL_COMPONENT_LINK_NOHTML', 'index2.php?option=com_joomleague&amp;no_html=1');
  
  define ( 'JL_ADMIN_TEMPLATE_PATH', JL_ADMIN_PATH.'/templates');
  
  define ( 'JL_ADMIN_COMPONENT_LINK', 'index2.php?option=com_joomleague');
  
  define ( 'JL_FUNCTIONS_PATH', JL_FRONTEND_PATH.'/lib');
  
  $Itemid = intval(mosGetParam($_REQUEST, 'Itemid', 0));
  if ($Itemid == 0) {
    $query = "SELECT id FROM #__menu WHERE link = '".JL_COMPONENT_LINK."' LIMIT 1";
    $database->setQuery($query);
    $Itemid = $database->loadResult();
  }
  // in update there now is a function which creates a componentlink if not already is there
  // to have a proper Itemid for JoomLeague
  define ('JL_ITEMID', intval($Itemid));
  define ('JL_ITEMID_SUFFIX', '&amp;Itemid='.$Itemid);
  
  // constand definition ends
  function _include(){
      
    $dirname = dirname(__FILE__) . '/classes';
    
    if ($dir = @opendir($dirname)) {
      require_once(sprintf("%s/%s",$dirname,"JLClass.class.php"));//has to be imported first
      while (($file = @readdir($dir)) !== false) {
        if (substr($file, -9) == 'class.php') {
          if (require_once(sprintf("%s/%s",$dirname,$file))) {
            //printf("%s/%s",$dirname,$file);
          }
          else {
            printf("could not include file: %s", $file);          
          }
        }
      }
  
      @closedir($dir);
    }
  }
  
  /**
   * get player history across all projects, with team, season, position,... info
   *
   * @param int $player_id
   * @param int $order ordering for season and league
   * @param string $filter e.g. "s.name = 2007/2008", default empty string
   * @return array of objects
   */
  function jl_getPlayerHistory($player_id, $order='ASC', $published = 1, $filter="") {
    global $database;
    if ($published) {
      $filter .= " AND p.published = 1 ";
    }
    $query = "SELECT pt.id AS ptid, pt.player_id AS pid, pt.team_id, pt.project_id, 
                     t.name AS teamname, 
                     p.name AS pname,
                     s.name AS sname,
                     tt.id AS ttid,
                     pos.name AS position 
              FROM #__joomleague_playertool AS pt
        			INNER JOIN #__joomleague AS p ON p.id = pt.project_id
        			INNER JOIN #__joomleague_seasons AS s ON s.id = p.season_id
        			INNER JOIN #__joomleague_leagues AS l ON l.id = p.league_id
        			INNER JOIN #__joomleague_teams AS t ON t.id = pt.team_id
        			INNER JOIN #__joomleague_team_joomleague AS tt ON pt.team_id = tt.team_id AND pt.project_id = tt.project_id
        			INNER JOIN #__joomleague_positions AS pos ON pos.id = pt.position_id
        			WHERE player_id='$player_id' $filter
        			GROUP BY pt.id ORDER BY s.ordering $order, l.ordering $order, p.name ASC";
    $database->setQuery($query);
    $info=$database->loadObjectList();
    return $info;
  }
  
  /**
   * get person history across all projects, with team, season, position,... info
   *
   * @param int $person_id , linked to player_id from Player object
   * @param int $order ordering for season and league
   * @param string $filter e.g. "s.name = 2007/2008", default empty string
   * @return array of objects
   */
  function jl_getStaffHistory($person_id, $order='ASC', $published = 1, $filter="") {
    global $database;
    if ($published) {
      $filter .= " AND p.published = 1 ";
    }
    $query = "SELECT ts.teamstaff_id AS tsid, ts.person_id AS pid, 
                     p.id AS project_id, 
                     t.name AS teamname, 
                     p.name AS pname,
                     s.name AS sname,
                     tt.id AS ttid,
                     pos.name AS position
              FROM	#__joomleague_teamstaff_project AS ts
        			INNER JOIN #__joomleague_team_joomleague AS tt ON tt.id = ts.projectteam_id
        			INNER JOIN #__joomleague AS p ON p.id = tt.project_id
        			INNER JOIN #__joomleague_seasons AS s ON s.id = p.season_id
        			INNER JOIN #__joomleague_leagues AS l ON l.id = p.league_id
        			INNER JOIN #__joomleague_teams AS t ON t.id = tt.team_id
        			INNER JOIN #__joomleague_positions AS pos ON pos.id = ts.position_id
        			WHERE person_id= '$person_id' $filter
        			GROUP BY ts.teamstaff_id ORDER BY s.ordering $order, l.ordering $order, p.name ASC
        			";
    $database->setQuery($query);
    $info=$database->loadObjectList();
    return $info;
  }
  
  function jl_quick_jump($project_id=0, $charlimit = false) {
    global $database;
    $selectoptions[]=mosHTML::makeOption( 0, _JL_ADMIN_QUICKJUMP );
    $query="SELECT p.id, CONCAT(l.name, ' ', s.name,' (', r.name, ')') AS projectname
            FROM #__joomleague AS p
            LEFT JOIN #__joomleague_leagues AS l ON p.league_id = l.id 
            LEFT JOIN #__joomleague_seasons AS s ON p.season_id = s.id 
            LEFT JOIN #__joomleague_rounds AS r ON p.current_round = r.matchcode 
            WHERE p.published=1 
            GROUP BY p.id
            ORDER BY s.ordering, l.ordering";
	  $database->setQuery($query);
		if ($project_list = $database->loadObjectList()) {
			
			for ($x=0;$x<count($project_list);$x++) {
		  	$p=$project_list[$x];
	      $selectoptions[] = mosHTML::makeOption(sefRelToAbs(JL_COMPONENT_LINK."&amp;p=".$p->id.JL_ITEMID_SUFFIX), $p->projectname); 
		 	}
		 	$projectlist = mosHTML::selectList( $selectoptions, 'p', "class=\"inputbox\" onchange=\"javascript:if(this.options[this.options.selectedIndex].value!=0) window.location.href=this.options[this.options.selectedIndex].value;\"",'value', 'text', sefRelToAbs(JL_COMPONENT_LINK."&amp;p=".$project_id.JL_ITEMID_SUFFIX) );
			echo '<br /><div style="text-align:right;clear:both;">'.$projectlist.'</div>';
		}
		
  }
  
  function jl_get_frontpage_projects( $seasonid, $limit=false ) 
  {
		global $database;

    $query = " SELECT p.id 
		           FROM #__joomleague AS p 
		           INNER JOIN #__joomleague_leagues AS l ON p.league_id = l.id 
		           WHERE published = 1 AND season_id = $seasonid 
               ORDER BY l.ordering";
		if ( $limit ) {
		  $query .= " LIMIT " . $limit;
		}
		
		$database->setQuery($query);
		$projects = $database->loadObjectList();
		return $projects;
	}
	
function jl_utf8_convert ($text) {

    switch (strtolower(_JL_ENCODING)) {
      case 'utf-8':
        return $text;
      break;
      case 'iso-8859-1':
        return utf8_encode($text);
      break;
      default:
        return (function_exists('iconv')) ? iconv(_JL_ENCODING, 'UTF-8', $text) : $text;
      break;
  }
}

/**
 * return html code for form to navigate in projects/rounds/teams
 *
 * @param object $project
 * @param int $round_id
 * @param int $teamtoolid
 * @param string $orderstring
 * @return html code
 */
function jl_getProjectsList(&$project,$round_id,$teamtoolid, $orderstring = NULL) {
  global $database;
  $project_id = ( $project ? $project->id : 0 ); // current project, if there is one
  $select_lists = '';
  $formstart = '<form action="index2.php" method="post" style="display:inline;width:100%;">';
  $formhiddens = '<input type="hidden" name="option" value="'.JL_OPTION.'">
                 <input type="hidden" id="jl_short_task" name="task" value="setactual" />
                 <input type="hidden" id="jl_short_act" name="act" value="" />
                 <input type="hidden" id="jl_navcid" name="cid[0]" value="" />
                 <input type="hidden" id="jl_adminmode" name="adminmode" value="'.JL_ADMIN_MODE.'" />
                 ';
  $formend = '</form>';
  $alljavascript = "if (this.value != 0) {document.getElementById('jl_navcid').value = this.value;this.form.submit();}";
  $adminmode[] = mosHTML::makeOption( 'league_management', _JL_ADMIN_LEAGUE_MANAGEMENT );
  $adminmode[] = mosHTML::makeOption( 'prediction_management', _JL_ADMIN_PREDICTION_MANAGEMENT );
  $myjavascript = "document.getElementById('jl_adminmode').value = this.value;";
  $select_lists = mosHTML::selectList( $adminmode, 'a_mode', 'class="inputbox" style="width:100%;" size="1" onchange="'.$myjavascript.$alljavascript.'"','value', 'text', JL_ADMIN_MODE );
  if (JL_ADMIN_MODE == 'league_management') {
    
  	$all_projects[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_PROJECT );
    $query = "SELECT p.name as text, p.id as value FROM #__joomleague AS p
         LEFT JOIN #__joomleague_seasons AS s ON p.season_id = s.id
         LEFT JOIN #__joomleague_leagues AS l ON p.league_id = l.id";
    if ($orderstring) $query .= $orderstring;
    else $query .= " ORDER BY s.ordering, l.ordering";
    if (!$database->setQuery( $query )) echo $database->getErrorMsg(); 
    $projects = array_merge ($all_projects, $database->loadObjectList());
    $myjavascript = "";
    $select_lists .= mosHTML::selectList( $projects, 'p_list', 'class="inputbox" style="width:100%;" size="1" onchange="'.$myjavascript.$alljavascript.'"','value', 'text', $project_id );
    unset ( $projects );

    if ( $project_id ) {      
      $myrounds = $project->getRoundNames();
      $avail_rounds[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_MATCHDAY );
      $rounds = array();
      if (count($myrounds) > 0){foreach($myrounds as $result){$rounds[] = mosHTML::makeOption($result->id, $result->name);}}
      $rounds = array_merge ($avail_rounds, $rounds);
      $myjavascript = "document.getElementById('jl_short_task').value = 'tab1';";
      $myjavascript .= "document.getElementById('jl_short_act').value = 'rounds';";
      $select_lists .= "\n".mosHTML::selectList( $rounds, 'r_list', 'class="inputbox" style="width:100%;" size="1" onchange="'.$myjavascript.$alljavascript.'"','value', 'text', $round_id );
      unset ( $rounds );
      $myteams = $project->getTeams();
      $avail_teams[] = mosHTML::makeOption( '0', _JL_ADMIN_SELECT_TEAM );
      $teams = array();
      if (count($myteams) > 0){foreach($myteams as $result){$teams[] = mosHTML::makeOption($result->teamtoolid, $result->name);}}
      $teams = array_merge ($avail_teams, $teams);
      $myjavascript = "document.getElementById('jl_short_act').value = 'teamtool';";
      $select_lists .= "\n".mosHTML::selectList( $teams, 'r_list', 'class="inputbox" style="width:100%;" size="1" onchange="'.$myjavascript.$alljavascript.'"','value', 'text', $teamtoolid );
      unset ( $teams );
    }
  }

    return $formstart."\n".$select_lists."\n".$formhiddens.$formend;
  }
  function mbiFormatDate( $date, $format="%x" ){
  	if ( $date != "0000-00-00" && ereg("([0-9]{4})-([0-9]{2})-([0-9]{2})", $date, $regs ) ) {
  		$date = strftime( $format, mktime(0,0,0,$regs[2], $regs[3], $regs[1]));
  	} else $date = '-';
  	return $date;
  }
  
  /**
   * returns number of years between 2 dates
   *
   * @param string $birthday date in YYYY-mm-dd format
   * @param string $current_date date in YYYY-mm-dd format, default to today
   * @return int age      
   */
  function getAge( $birthday, $current_date = null ) 
  {
    if ( $current_date == null || $current_date == '0000-00-00' ) {
      $current_date = date('Y-m-d');
    }
    
  	if ( $birthday == "0000-00-00" || !ereg("([0-9]{4})-([0-9]{2})-([0-9]{2})", $birthday, $regs ) ) {
      return '-';
    }
    
    $a_birthday = explode('-', $birthday);
    $a_today = explode('-', $current_date);
    
    $day_birthday = $a_birthday[2];
    $month_birthday = $a_birthday[1];
    $year_birthday = $a_birthday[0];
    $day_today = $a_today[2];
    $month_today = $a_today[1];
    $year_today = $a_today[0];
    
    $age = $year_today - $year_birthday;
    
    if (($month_today < $month_birthday) || ($month_today == $month_birthday && $day_today < $day_birthday)) {
        $age--;
    }
    
    return $age;
  }
  
  /**
   * returns the template file path from the template folder. First looks in 
   * /tmpl/ subfolder, then at the root of specified folder.   
   * If file doesn't exists, returns the file path from default folder.
   *
   * @param string $templateFolder
   * @param string $filename
   */
  function getTemplateFile($templateFolder, $filename) 
  {
  	if ( file_exists($templateFolder.'/tmpl/'.$filename) ) {
      return($templateFolder.'/tmpl/'.$filename);
    }
    else if ( file_exists($templateFolder.'/'.$filename) ) {
      return($templateFolder.'/'.$filename);
    }
    else {
      return(JL_FRONTEND_PATH.'/frontend/default/'.$filename);
    }
  }
  
}


_include();

?>
